package com.apps.ftapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apps.ftapp.R;
import com.apps.ftapp.model.AlipayModel;
import com.apps.ftapp.model.PreOrderModel;
import com.apps.ftapp.model.Uaddress;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tsy.sdk.pay.alipay.Alipay;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

public class OrderAddActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.order_shouhuoren)
    TextView orderShouhuoren;
    @BindView(R.id.order_dizhi)
    TextView orderDizhi;
    @BindView(R.id.order_address_container)
    RelativeLayout orderAddressContainer;
    @BindView(R.id.order_title)
    TextView orderTitle;
    @BindView(R.id.order_desc)
    TextView orderDesc;
    @BindView(R.id.order_price)
    TextView orderPrice;
    @BindView(R.id.order_img)
    ImageView orderImg;
    @BindView(R.id.order_mid_container)
    RelativeLayout orderMidContainer;
    @BindView(R.id.order_status)
    TextView orderStatus;
    @BindView(R.id.order_money)
    TextView orderMoney;
    @BindView(R.id.youhuiquan)
    TextView youhuiquan;
    @BindView(R.id.alipay)
    RelativeLayout alipay;
    @BindView(R.id.wechat)
    RelativeLayout wechat;
    @BindView(R.id.total_price)
    TextView totalPrice;
    @BindView(R.id.zhifu)
    Button zhifu;
    @BindView(R.id.selyouhuiquan)
    RelativeLayout selyouhuiquan;
    @BindView(R.id.genghuan)
    RelativeLayout genghuan;
    @BindView(R.id.add_mobile)
    TextView addMobile;
    @BindView(R.id.shouhuodizhi)
    TextView shouhuodizhi;
    @BindView(R.id.genggai)
    TextView genggai;
    @BindView(R.id.order_t)
    TextView orderT;

    private String youhuiquanid;
    private String addressId;

    private String icon;
    private String id;
    private String title;
    private String price;
    private String type;
    private String desc;
    private String endShopTime;

    private PreOrderModel jsonBean = new PreOrderModel();


    private Gson gson = new Gson();

    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;


    private boolean isSub = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_add);
        ButterKnife.bind(this);


        //显示图片的配置  
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        if (null != bundle) {
            //接收name值
            id = bundle.getString("id");
            icon = bundle.getString("icon");
            title = bundle.getString("title");
            price = bundle.getString("price");
            type = bundle.getString("type");
            desc = bundle.getString("desc");
            endShopTime = bundle.getString("endShopTime");
        }

        setTitle("订单确认");


        orderAddressContainer.setOnClickListener(this);
        selyouhuiquan.setOnClickListener(this);
        genghuan.setOnClickListener(this);
        zhifu.setOnClickListener(this);

        initVIew();


        loadData(id);

    }

    private void loadData(String id) {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.add("id", id);
        params.add("targetType", type);
        Async.post("course/buy", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    // L.i("main",new String(responseBody));
                    //请求成功

                    jsonBean = gson.fromJson(new String(responseBody), PreOrderModel.class);
                    if (1 == Tools.isIntNull(jsonBean.getSuccess())) {
                        youhuiquan.setText(jsonBean.getCoupons().getText());
                        if (jsonBean.getCourse().getBook().equals("1")) {
                            getloadData();
                        } else {
                            genghuan.setVisibility(View.GONE);
                            orderAddressContainer.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }

    private void initVIew() {

        totalPrice.setText("¥" + price);
        orderTitle.setText(title);
        orderPrice.setText("¥" + price);
        orderMoney.setText("实付：" + price + "元");

//        orderT.setText(tim);
        imageLoader.displayImage(icon, orderImg, options);


        orderDesc.setText(desc);
        orderT.setText(endShopTime);

        String address_name = Tools.isNull(SharedPreferencesUtil.getData(getApplicationContext(), "address_name", ""));
        String address_mobile = Tools.isNull(SharedPreferencesUtil.getData(getApplicationContext(), "address_mobile", ""));
        String address_address = Tools.isNull(SharedPreferencesUtil.getData(getApplicationContext(), "address_address", ""));
        String address_id = Tools.isNull(SharedPreferencesUtil.getData(getApplicationContext(), "address_id", ""));


        orderShouhuoren.setText("收件人：" + address_name);
        orderDizhi.setText("收货地址：" + address_address);
        addMobile.setText(address_mobile);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_address_container:

//                ActivitySkipUtil.skipAnotherActivity(OrderAddActivity.this,UserAddressListActivity.class,false);
                Intent mIntent = new Intent();
                mIntent.setClass(OrderAddActivity.this,
                        UserAddressListActivity.class);
                int requestCode = 0;
                startActivityForResult(mIntent, requestCode);

                break;


            case R.id.selyouhuiquan:


                if (null != jsonBean.getCoupons().getCouponslist() && jsonBean.getCoupons().getCouponslist().size() > 0) {
                    Intent mIntent1 = new Intent();
                    mIntent1.putExtra("state", "order");
                    mIntent1.setClass(OrderAddActivity.this,
                            MyCouponActivity.class);
                    int requestCode1 = 2;
                    startActivityForResult(mIntent1, requestCode1);
                }


                break;


            case R.id.genghuan:
                Intent mIntent2 = new Intent();
                mIntent2.setClass(OrderAddActivity.this,
                        UserAddressListActivity.class);
                int requestCode2 = 0;
                startActivityForResult(mIntent2, requestCode2);

                break;


            case R.id.zhifu:

                //付款
                zhifu();
                //付款

                break;

        }
    }


    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (null != data) {
            String name = data.getStringExtra("name");
            String mobile = data.getStringExtra("mobile");
            String address = data.getStringExtra("address");
            addressId = data.getStringExtra("addressId");
            // 根据上面发送过去的请求吗来区别
            switch (requestCode) {
                case 0:

                    orderShouhuoren.setText(name);
                    orderDizhi.setText(address);
                    addMobile.setText(mobile);
                    //

                    SharedPreferencesUtil.saveData(getApplicationContext(), "address_name", name);
                    SharedPreferencesUtil.saveData(getApplicationContext(), "address_mobile", mobile);
                    SharedPreferencesUtil.saveData(getApplicationContext(), "address_address", address);
                    SharedPreferencesUtil.saveData(getApplicationContext(), "address_id", addressId);


                    isSub = true;

                    break;

                case 2:
                    String address1 = data.getStringExtra("value");
                    youhuiquanid = data.getStringExtra("couponId");

                    double pp = Tools.round(Tools.isDoubleNull(price) - Tools.isDoubleNull(address1), 2);
                    totalPrice.setText("¥" + pp);
                    orderMoney.setText("实付：" + pp + "元");

                    youhuiquan.setText(address1);
//                orderDizhi.setText(address);

                    break;

            }
        }

    }


    private void getloadData() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("my/address", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    Uaddress result = gson.fromJson(new String(responseBody), Uaddress.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {

                        if (null != result.getAddress() && result.getAddress().size() > 0) {

                            if (!"".equals(Tools.isNull(orderShouhuoren.getText().toString()))) {
                                L.i("main", "获取收货地址");

                                orderShouhuoren.setText("收件人：" + result.getAddress().get(0).getUser_name());
                                orderDizhi.setText("收货地址：" + result.getAddress().get(0).getAddress());
                                addMobile.setText(result.getAddress().get(0).getMobile());
                                addressId = result.getAddress().get(0).getAddress_id();
                            }

                        }
//                        dataList.addAll(result.getAddress());
//                        userAddressAdapter.addRes(result.getAddress());
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }


    private void zhifu() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("targetId", id);
        if (!jsonBean.getCourse().getBook().equals("2")) {
            params.put("addressid", addressId);
        }
        //params.put("couponsid", youhuiquanid);
        params.put("targetType", type);
        params.put("payment", "alipay");

        L.i("main", "token::" + Constant.token + "::" + Constant.token);
        L.i("main", "targetId::" + id + "::addressid::::" + addressId + "：：：" + type);
        L.i("main", "payment::" + Constant.token + ":couponsid::::" + youhuiquanid);

        Async.post("order/create", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    AlipayModel result = gson.fromJson(new String(responseBody), AlipayModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        doAlipay(result.getStr());
                    } else {
                        String msg = Tools.isNull(result.getError());
                        if ("".equals(msg))
                            Toasty.normal(getApplicationContext(), "请填写地址，并确认快递信息完整 一旦发货不支持快递信息修改").show();
                        else
                            Toasty.normal(getApplicationContext(), msg).show();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));
            }
        });
    }


    /**
     * 支付宝支付
     *
     * @param pay_param 支付服务生成的支付参数
     */
    private void doAlipay(String pay_param) {
        new Alipay(this, pay_param, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                Toasty.normal(getApplicationContext(), "支付成功").show();
                ActivitySkipUtil.skipAnotherActivity(OrderAddActivity.this, MyOrderActivity.class, false);


            }

            @Override
            public void onDealing() {
                Toasty.normal(getApplicationContext(), "支付处理中...").show();

            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        Toasty.normal(getApplicationContext(), "支付失败:支付结果解析错误").show();
                        break;

                    case Alipay.ERROR_NETWORK:
                        Toasty.normal(getApplicationContext(), "支付失败:网络连接错误").show();
                        break;

                    case Alipay.ERROR_PAY:
                        Toasty.normal(getApplicationContext(), "支付错误:支付码支付失败").show();
                        break;

                    default:
                        Toasty.normal(getApplicationContext(), "支付错误").show();
                        break;
                }

            }

            @Override
            public void onCancel() {
                Toasty.normal(getApplicationContext(), "支付取消").show();

            }
        }).doPay();
    }

}
